<template>
  <div class="container-fluid_ setAccount">
    <el-form @validate='validateFn' :rules="rulesAcount"  ref="form" :model="formData">
      <div class="filter-container">
        <el-form-item label=""
          prop='name' class="filter-item">
          <el-input placeholder="Rate Card Name" style="width: 200px;" clearable @keyup.enter.native="handleFilter"
            v-model="formData.name" />
        </el-form-item>
     <!-- <el-button class="filter-item" type="success" icon="el-icon-search" @click="handleFilter">
       Search
     </el-button> -->

        <el-form-item label="" prop='remarks' class="filter-item" style="width: 200px;float: right;">
          <el-input placeholder="Rate Card Remark" class="filter-item" clearable @keyup.enter.native="handleFilter"
            v-model="formData.remarks" />
        </el-form-item>
      </div>
      <div class="cl">
        <el-form-item label="" prop='title' class="filter-item" >
          <el-input v-show='false' placeholder="Rate Card Remark" class="filter-item"
            v-model="formData.title" />
        </el-form-item>

        <div :key='li' v-for='(ils,li,i) in list.rateBody'>
          <h3 class="fl">{{i===3?'Half-day':i===2?'Daily':li.charAt(0).toUpperCase() + li.slice(1)}} Rate</h3>
          <h3 class="fr">
            <el-button type="success" @click='addList(li)'>Add</el-button>
          </h3>

          <el-table v-loading="listLoading" :data="ils" element-loading-text="loading" border fit highlight-current-row
            stripe @sort-change='that.sort_change'>
            <el-table-column fixed="left" :label="'Title'" prop="member">
              <template slot-scope="scope">
                <!-- <label class="label-md cur">Activities:</label>
                  <el-select v-model="info.activities" placeholder="Select">
                    <el-option v-for="item in ActivitiesList" :key="item.value" :label="item.typeName" :value="item.id" /></el-select></div>
              </el-form-item> -->
                <el-select v-model="scope.row.title" @change='(val)=>rateChange(val,scope,li)' :disabled="!scope.row.edit"
                  placeholder="Select Title">
                  <el-option v-for="item in RATE_TITLE" :key="item.id" :label="item.typeName"
                   :disabled="(hasSelTitleId[li+'_'+scope.$index]&& hasSelTitleId[li+'_'+scope.$index] === item.id ) || (!hasSelTitleId[li+'_'+scope.$index]&&JSON.stringify(hasSelTitleId).indexOf(item.id)>-1)"
                    :value="item.id" />
                </el-select>
                <!-- <span v-else>
                  {{scope.row.titleName}}
               </span> -->
              </template>
            </el-table-column>
            <!-- #endif -->
            <el-table-column :key='r' v-for='(rateTh,r) in list.titleName'  :label="rateTh.name" prop="member">
              <template slot-scope="scope"  >
                     <template v-if='spo.sport === rateTh.sport'   v-for='(spo,l) in scope.row.rateAndSport'  :hasEidt='hasEidt(scope.row,i,li,rateTh,r)'>


                <el-form-item label="" :key='l' v-if='scope.row.edit' validate-event inline-message style="margin:0;padding:0;"
                  :rules="[
                     {message:'Please enter ' + rateTh.name + 'aand only enter number' ,target:'change'}
                   ]"
                  :prop="li+rateTh.name+r">
                  <el-input type="text" @blur='(v)=>inpFn(v,spo,"_rate")' v-model="spo._rate"
                    v-if='spo&&spo.sport===rateTh.sport' />
                 <!-- <span v-else>
                    {{scope.row.rateAndSport | fixThTitle(list.titleName,r,$set)}}
                  </span> -->
                </el-form-item>
                <div v-else>
                  <span type="text" v-if='spo&&(spo.sport===rateTh.sport)'>{{spo.rate}}</span>
                 <!-- <span v-else>
                    {{spo}}{{rateTh}}
                    {{scope.row | fixThTitle(list.titleName,r,rateTh,$set)}}
                  </span> -->
                </div>
                 </template>
                 <template v-else-if='!scope.row.rateAndSport[r]'>
                    {{scope.row | fixThTitle(list.titleName,r,rateTh,$set)}}
                   <!-- <span type="text" v-if='spo&&(spo.sport===rateTh.sport)'>{{spo.rate}}</span> -->
                 </template>

              </template>
            </el-table-column>
            <el-table-column fixed="right" label="" width="100">
              <template slot-scope="scope">
                <EditDel :scope='scope' :option='{lisName:li,list:ils,hideOk:false,_del:true,_edit_:false,_edit_list:scope.row.rateAndSport}'
                  @confirmEdit="confirmEdit" @del="del" />
                <!-- <div  id="EditDel" style="text-align: center;" v-else>
               <el-button   type="text"   class="iconBtn" style="text-align: center;">
                 <i class="el-icon-error" @click="$set(scope.row,'');" />
               </el-button>
               </div> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>


      <!-- </router-link> -->

      <el-pagination layout="sizes, prev, pager, next" :page-size="that.listQuery.limit" :current-page="that.listQuery.page"
        :total="that.list.total" :page-sizes="[25, 50, 100]" @size-change="that.handleSizeChange" @current-change="that.handleCurrentChange"
        class="pagination-container" />
      <div class="t-center pad marTop btm-btn-groupss">
        <el-button type="success" size="medium" @click='$router.back(-1)'>Back</el-button>
        <el-button type="success" size="medium" @click='saveAccount'>Save</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
  import {
    getAccountBodyList,
    saveRateBody,
    getTypes,
    locGetAccountBodyList
  } from '@/api/setting'
  export default {
    name: 'RateCardEdit',
    data() {
      return {
        redirect: undefined,
        hasEidts: [0, 0, 0, 0],
        removeIds: [],
        //存储 已经操作过的 titleId
        hasSelTitleId: {},
        rulesAcount:{
           name:[{required: true, message: 'Please input Rate Card Name !', trigger:['blur']}],
           title:[{required: true, message: 'Please select Title !'}]
        },
        selectTitle:'',
        list: {
          rateBody: {
            hourly: [],
            session: [],
            dally: [],
            halfDay: []
          },

          titleName: []
        },
        RATE_TITLE: [], //（typeCode）

        formData: {
          remarks: '',
          name: '',
          title:'1',
        },
        inforname: {},
        listLoading: false,
        env: process.env.VUE_APP_ENV
      }
    },
    props: ['that'],
    watch: {
      formData: {
        handler(val) {
          // console.log('十大',val)
        },
        immediate: true
      },
      //监听 title 是否已经使用过 逻辑
      ['list.rateBody.dally']: {
        handler(vals) {
          this.readlRateBodyTitle(vals, 'dally')
        },
        immediate: false
      },
      ['list.rateBody.hourly']: {
        handler(vals) {
          this.readlRateBodyTitle(vals, 'hourly')
        },
        immediate: false
      },
      ['list.rateBody.halfDay']: {
        handler(vals) {
          this.readlRateBodyTitle(vals, 'halfDay')
        },
        immediate: false
      },
      ['list.rateBody.session']: {
        handler(vals) {

          this.readlRateBodyTitle(vals, 'session')
        },
        immediate: false
      },
      $route: {
        handler: function(route) {
          this.redirect = route.query && route.query.redirect
          this.query = route.query
        },
        immediate: true
      },
      ['list.rateBody.edit'](val) {
        console.log('val', val)
      }
    },
    created() {
      var that = this
      getTypes({
        code: 'RATE_TITLE'
      }).then((res) => {
        that.RATE_TITLE = res.result
      })
    },
    mounted() {

      this.fetchData(1)
    },
    updated(e) {
      //console.log('；updatedval',e,this);
      if (e) {
        // console.log('；updatedval',e)
      }
    },
    computed: {

    },
    methods: {
      readlRateBodyTitle(vals, session) {
        var hasSelTitleId = this.hasSelTitleId
          if (vals.length) {
            let val = vals
            for (var i = 0; i < val.length; i++) {
              if (val[i].title) {
                for (var k = 0; k < this.RATE_TITLE.length; k++) {
                  if (val[i].title === this.RATE_TITLE[k].id) {
                    hasSelTitleId[session + '_' + i] = val[i].title
                  }
                }
              }
          }
        }
      },
      rateChange(val, scope,name) {
        console.log("chaVal", val, scope,name)
        //this.hasSelTitleId[name+'_'+scope.$index] = val
        this.$set(this.hasSelTitleId,name+'_'+scope.$index,val)
      },
      findElem(arrayToSearch, attr, val) {
        //debugger
        console.log("evey", arrayToSearch, attr, val)
        // return arrayToSearch.every((item,ind ,ti)=>{
        //    console.log("ddddd", item,ind ,ti)
        //    let listIs = attr?item[attr]:item
        //    return listIs === val?{val,item:listIs}:-1
        //  })
        for (var i = 0; i < arrayToSearch.length; i++) {
          if (arrayToSearch[i][attr] == val) {
            arrayToSearch[i][attr] = ''
            return i; //返回当前索引值
          }
        }
        return -1
      },
      inpFn(v, rate, n) {
        let val = rate[n]
        //console.log("rate",typeof(rate), Number(val))
      //  var s = Number(val) ? Number(val) : 0
      //  this.$set(rate, n, s)
        //console.log("rate",val,typeof(val))
        // val = Number(val)?Number(val):0

        // =Number(scope.row.rateAndSport[r].rate)?Number(scope.row.rateAndSport[r].rate):0
      },
      validateFn(val, y) {
        var accountCard = this.list.accountCard
        var rateBody = this.list.rateBody
        //console.log('sdas ',val,y,rateBody)
      },
      hasEidt(val, i, li, rateTh, r) {
        //val.edit
        // this.$set(val.rateAndSport[r],"rate",Number(val.rateAndSport[r].rate))
        //console.log("hasEidt",typeof(val.rateAndSport[r].rate) )
        //this.hasEidts[i] = 1
        //this.inforname[li + rateTh.name + r] = 0
      },
      confirmEdit(e, editFn) {
           debugger
          this.formData.title = e.title
          if(!e.title){
           return this.$message({message:'Please select Title'})
          }
        for(let i in e.rateAndSport){
          if(i.indexOf('_')>-1){
             delete(e.rateAndSport['_'+i])
                      }

           delete(e.rateAndSport[i]['_sport'])
           delete(e.rateAndSport[i]['_rate'])
        }
        this.$set(e,'rateAndSport',e.rateAndSport)
        debugger
        console.log("row", e, this)
        // let {titleName:name, name:key, remarks, id, uts,rateAndSport} =e
        // let rateBody={[key]:rateAndSport}//JSON.stringify({[key]:rateAndSport})
        // saveRateBody({name,remarks,rateBody,id,uts})
      },
      del(e, ind, scope,that) {
        if(that.option.lisName){
          delete(this.hasSelTitleId[that.option.lisName+'_'+ind])
        }
        if (e) this.removeIds.push(e)
      },
      saveAccount() {
        let id = this.query.id ? this.query.id : '',
          {
            accountCard,
            rateBody
          } = this.list,
          params
        let uts = accountCard && this.query.id ? accountCard.uts : undefined;

      var _rateBody={}
     for(let kab in rateBody){
       let rateBodyKab = rateBody[kab]
        _rateBody[kab] =[]
        rateBodyKab.map((list)=>{

          let {id,rateAndSport,title} = list
           _rateBody[kab].push({id,rateAndSport,title})
       })
     }

        params = {
          name:this.formData.name,
          remarks:this.formData.remarks,
          rateBody: _rateBody,
          id,
          removeIds: this.removeIds
        }
        if (uts) {
          params.uts = uts
        }

      console.log('params account----',params,this.list)
        var that = this
        this.$refs['form'].validate((res) => {
          if (res) {
            let msg = that.query.id ? "Are you sure to save the rate card? When you click the Save button, all courses of the month will be affected" : 'Do you confirm to save?';
            this.$confirm(msg).then(() => {
              saveRateBody(params).then(() => {
                this.$router.push('/setting/Account/')
              }).catch(() => {

              })
            }).catch(() => {})


          } else {
            console.log('err!', res)
          }
        })
      },

      addList(rateName) {
        let data = this.list;
        let rateBody = data.rateBody[rateName]
        if (rateBody.length >= 0 && rateBody) {
          let b = {
            rateAndSport: [],
            id: 0,
            title: '',
            edit:true
          }
          data.titleName.map(lis => {
            b.rateAndSport.push({
              sport: lis.sport,
              rate: 0
            })
          })
          rateBody.push(b)
        }
      },
      fetchData(page) {
        this.listLoading = true;
        var that = this
        getAccountBodyList(this.query.id).then(response => {
          let data = response.result
          debugger
          if (!data.total && data.total === undefined) {
            data.total = that.list.total
          }

          if (that.query.id) {
            that.formData.name = data.accountCard.name
            that.formData.remarks = data.accountCard.notes
          }
          //data = locGetAccountBodyList.result

          // for(let i in data.rateBody){
          //   if(!data.rateBody[i].length&&data.rateBody[i]){
          //       let b={rateAndSport:[],title:'',titleName:''}
          //      data.titleName.map(lis=>{
          //      b.rateAndSport.push({sport:lis.sport,rate:0})
          //      })
          //       data.rateBody[i][0]=b
          //   }
          // }
          let {
            hourly,
            session,
            dally,
            halfDay
          } = data.rateBody
          var _rateBody = {
            hourly,
            session,
            dally,
            halfDay
          } //{Hourly:hourly,Session:session,Ddally:dally,'Half-day':halfDay}
          data.rateBody = _rateBody
          console.log("阿松大", data,this.hasSelTitleId)
          // if(){

          // }
          that.list = data
           // debugger
          that.listLoading = false
        })
      },

    }
  }
</script>

<style lang="scss">
  .setAccount {
    .el-form-item__error {
      position: initial;
    }
  }
</style>
